
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from pathlib import Path
from matplotlib import font_manager as fm
import matplotlib as mpl

# 尝试设置常见的中文字体作为后备，避免中文/全角标点缺字警告
candidates = ['SimHei', 'Microsoft YaHei', 'Noto Sans CJK SC', 'WenQuanYi Zen Hei', 'DejaVu Sans']
available_fonts = {f.name for f in fm.fontManager.ttflist}
for name in candidates:
    if name in available_fonts:
        mpl.rcParams['font.sans-serif'] = [name]
        break

# 保证负号显示正常
mpl.rcParams['axes.unicode_minus'] = False
# 估算站点与海拔（米）——如果你有 GPX 或经纬度可替换为精确值
stations = ['长安',
    '周至', '眉县', '陈仓', '渭滨', '凤县', '两当', '徽县', '成县', '天水南', '兰州西', '桑科草原', '拉卜楞寺', '甘加'
]
_elev = [425, 700, 600, 550, 550, 1200, 1400, 1600, 1500, 1100, 1550, 3100, 2900, 3300]

# 累计距离估算（若无真实 GPX，则用站点间估算距离作为等间距）
# 这里我们假设站点间大致等距；如果你有实际里程请替换 distances 列表
distances = [i for i in range(len(stations))]

plt.figure(figsize=(12,5), dpi=150)
plt.plot(distances, _elev, '-o', color='#d62728')
for x, y, name in zip(distances, _elev, stations):
    plt.text(x, y+80, name, ha='center', fontsize=8, rotation=25)

plt.fill_between(distances, _elev, color='#ffcccc', alpha=0.4)
plt.grid(True, linestyle='--', alpha=0.4)
plt.ylabel('海拔 (m)')
plt.xlabel('站点序列')
plt.title('估算路线海拔剖面 (基于近似海拔)')
plt.xticks(distances, [])

# 标注最高/最低点
max_h = max(_elev)
min_h = min(_elev)
max_idx = _elev.index(max_h)
min_idx = _elev.index(min_h)
plt.annotate(f'Max {max_h}m', xy=(distances[max_idx], max_h), xytext=(distances[max_idx], max_h+300),
             arrowprops=dict(arrowstyle='->'))
plt.annotate(f'Min {min_h}m', xy=(distances[min_idx], min_h), xytext=(distances[min_idx], min_h-500),
             arrowprops=dict(arrowstyle='->'))

# 保存图片
out_png = str(Path(__file__).resolve().parent / 'elevation_profile.png')
plt.tight_layout()
plt.savefig(out_png)
print('Saved elevation profile to', out_png)
